package cn.com.nes.site.listener;

import cn.com.nes.site.entity.em.*;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

public class ProtocolEnumWriteHandler implements SheetWriteHandler {
    private final int size;

    public ProtocolEnumWriteHandler(int size) {
        this.size = size;
    }

    public int order() {
        return OrderConstant.DEFAULT_ORDER;
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        // 获取列 寄存器类型
        Sheet sheet = context.getWriteSheetHolder().getSheet();

        // 设置 寄存器类型 下拉框
        setDropDownList(sheet, 1, size, 4, RegisterTypeEnum.values());

        // 设置 数据类型 下拉框
        setDropDownList(sheet, 1, size, 6, DataType.values());

        // modify by zhouy
        setDropDownList(sheet, 1, size, 5, ReadWriteEnum.values());

        setDropDownList(sheet, 1, size, 8, ShiFou.values());
    }

    private void setDropDownList(Sheet sheet, int firstRow, int lastRow, int col, ExcelEnum[] enums) {
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, col, col);
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 设置下拉框数据
        String[] list = new String[enums.length];
        for (int i = 0; i < enums.length; i++) {
            list[i] =  enums[i].cellName();
        }

        // 设置下拉框
        final DataValidationConstraint constraint = helper.createExplicitListConstraint(list);
        sheet.addValidationData(helper.createValidation(constraint, addressList));
    }

}
